<template>
  <a-modal
    :title="model && model.id ? '修改任务':'新建任务'"
    :width='640'
    :visible='visible'
    :confirmLoading='loading'
    @ok="() => { $emit('ok') }"
    @cancel="() => { $emit('cancel') }"
  >
    <a-spin :spinning='loading'>
      <a-form :form='form' v-bind='formLayout'>
        <a-form-item label='主键' v-show='false'>
          <a-input v-decorator="[
              'id'
            ]"></a-input>
        </a-form-item>

        <a-form-item label='任务名称'>
          <a-input placeholder='请输入任务名称' v-decorator="[
              'taskName',
              { rules: [
                { required: true, message: '请输入任务名称!' },
                { pattern: namePattern,  message: '请输入合法内容(可输入0到50位（中文、字母，数字，下划线，减号)'}
               ]
              }]"></a-input>
        </a-form-item>
        <a-form-item label='算法调用'>
          <a-select style='width: 100%;' placeholder='请选择算法' :options='allAlgorithmTaskList'
                    v-decorator="['algorithmTaskId', { rules: [{ required: true, message: '请选择对应算法!' }] },]">
          </a-select>
        </a-form-item>
        <a-form-item label='任务说明'>
          <a-textarea
            placeholder='任务说明'
            :auto-size='{ minRows: 3, maxRows: 5 }'
            v-decorator="['taskDesc']" />
        </a-form-item>
      </a-form>
    </a-spin>
  </a-modal>
</template>

<script>
import { findAllAlgorithmTask } from '@/api/algorithmTask'
import pick from 'lodash.pick'
import { namePattern } from '@/reges/index'

// 表单字段

const fields = ['id', 'taskName', 'algorithmTaskId', 'taskDesc']

export default {
  props: {
    visible: {
      type: Boolean,
      required: true
    },

    loading: {
      type: Boolean,
      default: () => false
    },
    model: {
      type: Object,
      default: () => null
    },
    moduleId: {
      type: String
    }
  },
  data () {
    this.formLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 3 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 21 }
      }
    }
    return {
      namePattern,
      form: this.$form.createForm(this),
      allAlgorithmTaskList: []
    }
  },
  methods: {
    async findAllAlgorithmTask () {
      const result = await findAllAlgorithmTask({ moduleId: this.moduleId })
      console.log(result, 'resule')
      this.allAlgorithmTaskList = result.map(item => {
        return {
          label: item.taskname,
          value: item.id
        }
      })
    }
  },
  created () {
    this.findAllAlgorithmTask()
    // 防止表单未注册
    fields.forEach(v => this.form.getFieldDecorator(v))

    // 当 model 发生改变时，为表单设置值
    this.$watch('model', () => {
      this.model && this.form.setFieldsValue(pick(this.model, fields))
    })
  }
}
</script>
